var {conNoArgs, getOpenid, con, uploadpic} = require("./request.js");
// var {uploadFile} = require("./upload.js");
var http = require("http");
var qiniu = require('qiniu')
var formidable = require('formidable')
var dateFormat = require('dateformat')
var express = require("express");
var fs = require('fs')
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({extended: false})
//解析url
var url = require("url");
//请求服务器的request
var request = require("request");
//引入mysql
var mysql = require("mysql");
var uuid = require("node-uuid");
//初始化express
var app = express();
app.all("*", (req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,username");
    res.setHeader("Access-Control-Allow-Methods", 'PUT, GET, POST, DELETE, OPTIONS');
    next();
})
//连接mysql
var connection = mysql.createConnection({
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'zqh521520.',
    database: 'test'
});
connection.connect();

//0.根据用户的code获取用户的信息
app.get("/getByCode", async function (req, res) {
    //1.通过url获取参数信息{ js_code: '043Cmcwk0mRyKo1XWhyk0t0hwk0Cmcw7' }
    var params = url.parse(req.url, true).query;
    let js_code = params.js_code;
    //2.请求微信的api获取用户信息
    var url_2 = "https://api.weixin.qq.com/sns/jscode2session?appid=wx59026a85ef30f6c9&secret=46a93376629d45fabcb4c73ba839f393&js_code=" + js_code + "&grant_type=authorization_code";
    //3.获取到了用户的 openid和session_key
    var res_2 = await getOpenid(request, url_2);
    var session_key = res_2.session_key;
    console.log(session_key)
    //4.根据session_key 查询用户信息
    var sql_3 = "select * from user_info where session_key = ";
    var params = ['' + session_key + ''];
    var res_3 = await con(sql_3, params);
    console.log(res_3)

});
//一.获取轮播图信息
app.get("/getSwiper", async function (req, res) {
    //1.定义sql语句
    var sql = "select * from swiper";
    //2.查询
    connection.query(sql, function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析返回的RowDataPacket
        var swiper = JSON.stringify(result);
        res.end(swiper);
    });
});


//二.获取首页  分类导航信息
app.get("/getCategory", function (req, res) {
    //1.定义sql语句
    var sql = "select * from category_list";
    //2.查询
    connection.query(sql, function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析返回的RowDataPacket
        var categoryList = JSON.stringify(result);
        res.end(categoryList);
    });
});


//三.获取商品列表信息  根据cid的不同返回不同的 排序方式
//如果有type_id ，证明从分类导航请求的，需要根据type_id请求不同类型的店铺
app.get("/storeList", async function (req, res) {
    //0.获取请求的参数   cid  pageSize pageNum
    var p = url.parse(req.url, true).query;
    var type_id = p.type_id;
    var pageSize = p.pageSize; //每页查询记录数
    var index = (p.pageNum - 1) * pageSize; //起始索引
    var params;
    //1.定义sql语句
    var sql;
    if (type_id == undefined) {
        // console.log("s首页查询")
        params = [index, parseInt(pageSize)];
        if (p.cid == 0) {
            sql = "select * from store_msg order by store_id limit ? , ?";
        } else if (p.cid == 1) {
            sql = "select * from store_msg order by score limit ? , ?";
        } else {//cid = 2 价格
            sql = "select * from store_msg order by perCapita limit ? , ?";
        }
    } else {
        // console.log("分类查询")
        params = [type_id, index, parseInt(pageSize)];
        if (p.cid == 0) {
            sql = "select * from store_msg where type_id = ? order by store_id limit ? , ?";
        } else if (p.cid == 1) {
            sql = "select * from store_msg where type_id = ? order by score limit ? , ?";
        } else {//cid = 2 价格
            sql = "select * from store_msg where type_id = ? order by perCapita limit ? , ?";
        }
    }
    //2.查询
    var res_1 = await con(sql, params);
    var store_list = JSON.stringify(res_1);
    res.end(store_list);
    /* connection.query(sql, params, function (error, result) {
         //出错了直接return
         if (error) {
             console.log(error);
             return;
         }
         //解析返回的RowDataPacket
         var storeList = JSON.stringify(result);
         // console.log(storeList);
         res.end(storeList);
     });*/
});
//四.获取总页数
app.get("/getTotalNum", function (req, res) {
    //1.定义sql语句
    var sql = "select count(*) as totalNum from store_msg";
    //2.查询
    connection.query(sql, function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var totalNum = JSON.stringify(result);
        res.end(totalNum);
    });
});
//五:获取订单列表信息  根据phoneNum获取
app.get("/getOrderList", function (req, res) {
    //0.获取用户电话
    let {phoneNum} = url.parse(req.url, true).query;
    // console.log(phoneNum);
    if (phoneNum == 'undefined') {
        res.end("no phoneNum")
        return;
    }
    //1.定义sql语句
    var sql = "SELECT * FROM order_list WHERE user_id = (SELECT user_id FROM user_info WHERE phoneNum = ?)";
    //2.查询
    connection.query(sql, [phoneNum], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var orderList = JSON.stringify(result);
        res.end(orderList);
    });
});

//六:服务端根据电话获取到用户id  再根据用户id查询收藏集合, 再根据收藏集合获取收藏的店铺信息
app.get("/getCollectionStoreFood", async function (req, res) {
    //0.获取用户电话
    let {phoneNum, index} = url.parse(req.url, true).query;
    // console.log(phoneNum);
    // console.log(index);
    //1.判断电话是否没定义
    if (phoneNum == 'undefined') {
        res.end("no phoneNum")
        return;
    }
    //index = 0表示店铺收藏  1表示商品收藏  3表示只获取收藏的信息并返回
    var params_1 = [phoneNum];
    if (index == 0) {
        //1.获取店铺收藏的列表
        //1.1定义sql
        var sql_1 = "select * from store_msg where store_id in(select store_id from collection_store_food where user_id = (SELECT user_id FROM user_info WHERE phoneNum = ?))";
        //1.2执行sql
        var collectionStore = await con(sql_1, params_1);
        //1.3 解析返回值
        collectionStore = JSON.stringify(collectionStore);
        // 1.4 返回信息
        res.end(collectionStore);
    } else if (index == 1) {
        //2.获取商品收藏的列表
        //2.1定义sql
        var sql_2 = "select * from food_detail where food_id in(select food_id from collection_store_food where user_id = (SELECT user_id FROM user_info WHERE phoneNum = ?))";
        //2.2执行sql
        var collectionFood = await con(sql_2, params_1);
        //2.3 解析返回值
        collectionFood = JSON.stringify(collectionFood)
        // 2.4 返回信息
        res.end(collectionFood);
    } else if (index == 3) {
        //3.1.定义sql语句
        var sql_3 = "SELECT * FROM collection_store_food WHERE user_id = (SELECT user_id FROM user_info WHERE phoneNum = ?)";
        //3.2.查询
        var res_3 = await con(sql_3, params_1);
        //3.3解析参数
        res_3 = JSON.stringify(res_3);
        // var collectionStoreFood = JSON.parse(res_3);
        //3.4 返回信息
        res.end(res_3);
    }
});
// 七: 用户反馈
app.post("/feedBack", function (req, res) {
    var body = "";
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        //解析参数
        body = JSON.parse(body);
        // console.log(body);
        // console.log(body.name);

        if (body == null) {
            return;
        }
        //添加参数到params
        var sql = "insert into feed_back values(null,?)";
        var params = [body.feed_back];
        // console.log(body.name);
        // console.log(params);
        connection.query(sql, params, function (error, result) {
            if (error) {
                console.log("something error");
                return;
            }
            if (result == null) {
                //结果为空
                console.log("result is null");
            }
            // console.log(result);
        });
        //关闭断开连接
        // connection.end();

        //可以返回数据
        res.end("success");


    });
});


//八:获取店铺信息
app.get("/getStoreMsgByStoreId", function (req, res) {
    //0.获取用户电话
    let {store_id} = url.parse(req.url, true).query;
    // console.log(store_id);
    if (store_id == 'undefined') {
        res.end("no store_id")
        return;
    }
    //1.定义sql语句
    var sql = "SELECT * FROM store_msg WHERE store_id = ?";
    //2.查询
    connection.query(sql, [store_id], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var storeMsg = JSON.stringify(result);
        // console.log(storeMsg);
        res.end(storeMsg);
    });
});

//九: 获取分类信息
app.get("/getFoodCateByStoreId", function (req, res) {
    // console.log("来了老弟")
    //0.获取用户电话
    let {store_id} = url.parse(req.url, true).query;
    // console.log(store_id);
    if (store_id == 'undefined') {
        res.end("no store_id")
        return;
    }
    //1.根据店铺id查询分类的信息
    var sql = "SELECT * FROM food_cate WHERE store_id = ? AND parrent_id = '0'";
    //2.查询
    connection.query(sql, [store_id], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var cate = JSON.stringify(result);
        // console.log(cate);
        res.end(cate);
    });
});
//十:根据分类的id获取对应商品的集合
app.get("/getFoodByFoodId", function (req, res) {
    //0.获取用户电话
    let {food_id} = url.parse(req.url, true).query;
    // console.log(store_id);
    if (food_id == 'undefined') {
        res.end("no food_id")
        return;
    }
    //1.根据店铺id查询分类的信息
    var sql = "SELECT * FROM food_cate WHERE parrent_id = ?";
    //2.查询
    connection.query(sql, [food_id], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var foods = JSON.stringify(result);
        // console.log(foods);
        res.end(foods);
    });
});

//十一：根据商品id查询商品详情信息
app.get("/getFoodDetailByFoodId", function (req, res) {
    //0.获取用户电话
    let {food_id} = url.parse(req.url, true).query;
    // console.log(store_id);
    if (food_id == 'undefined') {
        res.end("no food_id")
        return;
    }
    //1.根据店铺id查询分类的信息
    var sql = "SELECT * FROM food_detail WHERE food_id = ?";
    //2.查询
    connection.query(sql, [food_id], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var foods = JSON.stringify(result);
        // console.log(foods);
        res.end(foods);
    });
});

//十二 :搜索商品   模糊查询
app.get("/searchGoods", function (req, res) {
    //0.获取搜索对象
    let {query} = url.parse(req.url, true).query;
    // console.log(query);
    if (query == 'undefind') {
        res.end("no query")
        return;
    }
    query = "%" + query + "%";
    //1.根据店铺id查询分类的信息
    var sql = "SELECT * FROM food_detail WHERE food_name LIKE ?";
    //2.查询
    connection.query(sql, [query], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var querys = JSON.stringify(result);
        // console.log(querys);
        res.end(querys);
    });
});


//十三 : 更新收藏的信息
app.post("/updateCollectionFoodStore", async function (req, res) {
    //1.获取电话号码
    var {phoneNum, type} = url.parse(req.url, true).query;
    // console.log(type);
    // 2.根据电话  获取用户id
    var sql_1 = "select user_id from user_info  where phoneNum = ?";
    var re_1 = await con(sql_1, [phoneNum]);
    var {user_id} = re_1[0];
    //3.接收post请求的参数   { choose_collect: true, food_id: 2 }
    var body = await reqon(req, res);
    //4.查询是否存在  该收藏  type=1表示店铺收藏  type= 2表示商品收藏
    // console.log(body);
    if (type == 1) {
        //6.0: 如果choose_collect是true表示 收藏,  false表示取消收藏
        if (body.choose_collect) {
            //添加商品收藏
            var sql_2 = "insert into collection_store_food values(?,?,?)";
            var params_2 = [user_id, body.store_id, null];
            await con(sql_2, params_2);
            res.end("");
        } else {
            //删除商品收藏
            var sql_3 = "delete from collection_store_food where user_id = ? and store_id = ?";
            var params_3 = [user_id, body.store_id];
            await con(sql_3, params_3);
            res.end("");
        }
    } else if (type == 2) {
        //6.1: 如果choose_collect是true表示 收藏,  false表示取消收藏
        if (body.choose_collect) {
            //添加商品收藏
            var sql_4 = "insert into collection_store_food values(?,?,?)";
            var params_4 = [user_id, null, body.food_id];
            await con(sql_4, params_4);
            res.end("");
        } else {
            //删除商品收藏
            var sql_5 = "delete from collection_store_food where user_id = ? and food_id = ?";
            var params_5 = [user_id, body.food_id];
            await con(sql_5, params_5);
            res.end("");
        }
    }
});


//十四: 获取购物车信息
app.get("/getCars", async function (req, res) {
    // console.log("进来吧")
    //1.获取电话号码
    var {phoneNum} = url.parse(req.url, true).query;
    // 2.获取用户id
    var sql_1 = "select user_id from user_info  where phoneNum = ?";
    var re_1 = await con(sql_1, [phoneNum]);
    var {user_id} = re_1[0];
    //3.根据用户id查询购物车信息
    var sql_2 = "select * from cars where user_id = ?";
    var re_2 = await con(sql_2, [user_id]);
    re_2 = JSON.stringify(re_2);
    res.end(re_2);
});

//十五: 更新购物车信息(先根据用户id删除购物车信息, 再添加购物车信息)
app.post("/updateCars", async function (req, res) {
    // console.log("进来 咯")
    //1.获取电话号码
    var {phoneNum} = url.parse(req.url, true).query;
    // 2.获取用户id
    var sql_1 = "select user_id from user_info  where phoneNum = ?";
    var re_1 = await con(sql_1, [phoneNum]);
    var {user_id} = re_1[0];
    if(user_id == 'undefined'||user_id == null){
        res.end('')
    }
    //3.删除所有的购物车信息  根据用户id
    var sql_2 = "delete from cars where user_id = ?";
    await con(sql_2, [user_id]);
    //4.获取客户端传入过来的购物车信息  购物车数组
    let {cars} = await reqon(req, res);
    // console.log(cars);
    //5.添加购物车的信息
    var sql_3 = "insert into cars values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    cars.forEach(async (v) => {
        var params = [null, v.store_id, v.food_id, v.store_img_url, v.food_name, v.food_msg, v.food_pic, v.storeName, v.food_sales, v.food_price, v.choose_collect, v.num, v.checked, user_id];
        await con(sql_3, params);
    })
    res.end("");
});
//十六:更新订单列表信息, 添加订单列表(根据用户id)
app.post("/updateOrderList", async function (req, res) {
    // console.log("好吧")
    //1.获取电话号码
    var {phoneNum} = url.parse(req.url, true).query;
    // 2.获取用户id
    var sql_1 = "select user_id from user_info  where phoneNum = ?";
    var re_1 = await con(sql_1, [phoneNum]);
    var {user_id} = re_1[0];
    //4.获取客户端传入过来的购物车信息  购物车数组
    let {pay} = await reqon(req, res);
    // console.log(pay);
    //5.添加订单列表信息
    var sql_3 = "insert into order_list values(?,?,?,?,?,?,?,?,?,?,?)";
    pay.forEach(async (v) => {
        var order_id = uuid.v4();
        var params = [null, order_id, v.store_id, v.store_img_url, v.storeName, v.orderDate, v.food_name, v.orderInformation, v.totalPrice, v.totalNum, user_id];
        // console.log(params);
        await con(sql_3, params);
    })
    res.end("");
});
//十六:更新订单列表信息, 添加订单列表(根据用户id)
app.get("/deleteOrderList", async function (req, res) {
    //1.获取电话号码
    var {phoneNum, order_id} = url.parse(req.url, true).query;
    // 2.获取用户id
    var sql_1 = "select user_id from user_info  where phoneNum = ?";
    var re_1 = await con(sql_1, [phoneNum]);
    var {user_id} = re_1[0];
    //4.根据用户id和订单id删除订单信息
    var sql_2 = "delete from order_list where order_id = ? and user_id = ?";
    var params = [order_id, user_id];
    await con(sql_2, params);
    res.end("");
});
//十七，添加用户  先根据手机号查询是否存在，存在更新，不存在添加
app.post("/updateUser", async function (req, res) {
    //1.获取post的参数
    var {userInfo} = await reqon(req, res);
    // console.log(userInfo);
    //2.根据电话号码查询该用户是否存在
    var sql_2 = "select * from user_info where phoneNum = ?";
    var res_2 = await con(sql_2, [userInfo.phoneNum]);
    if (res_2.length < 1) {
        //用户不存在,添加用户
        var sql_3 = "insert into user_info values(?,?,?,?,?,?,?,?,?,?)"
        var params = [null, userInfo.nickName, userInfo.gender, userInfo.language, userInfo.city, userInfo.province, userInfo.country, userInfo.avatarUrl, null, userInfo.phoneNum];
        await con(sql_3, params);
    } else {
        // 用户存在,更新用户
        var sql_4 = "update user_info set nickName = ?,gender = ?, address = ? where phoneNum = ?";
        await con(sql_4, [userInfo.nickName, userInfo.gender, userInfo.address, userInfo.phoneNum]);
    }
    res.end("");
});


//------------------------------------------------------------------------------------------------------------------------
//一：登录操作
app.post('/store/login', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var username = req.body.username;
    var password = req.body.password;
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select store_id from store_back where username = ? and password = ?';
    var params = [username, password];
    var res_1 = await con(sql_1, params);
    if (res_1.length > 0) {
        //可以查到
        var {store_id} = res_1[0];
        var result = {flag: true, message: 'login success', store_id: store_id}
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    } else {
        //查不到或者查找错误
        var result = {flag: false, message: 'no such account'}
        var string = JSON.stringify(result);
        res.end(string)
    }
})

//一：登录操作
app.post('/store/login', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var username = req.body.username;
    var password = req.body.password;
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select store_id from store_back where username = ? and password = ?';
    var params = [username, password];
    var res_1 = await con(sql_1, params);
    if (res_1.length > 0) {
        //可以查到
        var {store_id} = res_1[0];
        var result = {flag: true, message: 'login success', store_id: store_id}
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    } else {
        //查不到或者查找错误
        var result = {flag: false, message: 'no such account'}
        var string = JSON.stringify(result);
        res.end(string)
    }
})
//二：注册操作
app.post('/regist/store', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var username = req.body.username;
    var password = req.body.password;
    var phone_num = req.body.phone_num;
    // console.log(username)
    // console.log(password)
    // console.log(phone_num)
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select store_id from store_back where username = ?';
    var params_1 = [username];
    var res_1 = await con(sql_1, params_1);
    if (res_1.length > 0) {
        //3.可以查到 该账号被注册过了
        var result = {flag: false, message: '该账号已注册'}
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    } else {
        //4.查不到  账号可以注册
        var sql_2 = 'insert into store_back values(?,?,?,?)'
        var params_2 = [null, username, password, phone_num]
        var res_2 = await con(sql_2, params_2)
        //5. 把用户id的注册信息写入店铺信息
        // console.log(res_2.insertId)
        var result = {flag: true, message: '注册成功'}
        var string = JSON.stringify(result);
        //6. 注册成功以后会返回店铺id 操作
        var sql_3 = 'insert into store_msg (store_id , score) values(?,?)'
        var paramss_3 = [res_2.insertId, 4.5]
        await con(sql_3, paramss_3)
        res.end(string)
    }
})
//三：上传图片  返回图片id来预览
app.post('/storehead/upload', urlencodedParser, async function (req, res) {
    //1.使用formidable 框架接收图片信息
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8'
    form.maxFieldsSize = 4 * 1024 * 1024
    form.keepExtensions = true //保留后缀
    form.parse(req, async function (err, fields, files) {
        //2.文件路径
        var path = files.file.path
        //3.1时间戳 作为名字
        var name_head = Date.now()
        // console.log(name)
        //3.2 获取图片后缀
        var split = files.file.name.split('.');
        // console.log(split[1])
        //3.3 定义输出图片的名称
        var key = name_head + '.' + split[1]
        //4.把上传的图片信息写到本地
        // fs.writeFileSync("./images/" + key, fs.readFileSync(files.file.path))
        //5. 填写 账号密码
        //需要填写你的 Access Key 和 Secret Key
        qiniu.conf.ACCESS_KEY = 'r8eR81kBwjteO4dWHCXDQafofk9KbtH65xQGZsBk';
        qiniu.conf.SECRET_KEY = 'av9H_BxKDAedyKzob7ZOr_9MdC6iBQ7UVGPmknfE';
        //要上传的空间
        bucket = 'xhkcwechat';

        // 上传图片---构建上传策略函数
        function uptoken(bucket, key) {
            // var putPolicy = new qiniu.rs.PutPolicy({scope:bucket+":"+key});
            const putPolicy = new qiniu.rs.PutPolicy({isPrefixalScope: 1, scope: bucket + ':' + key})
            return putPolicy.uploadToken();
        }

        const config = new qiniu.conf.Config()
        //七牛上传的token
        var up_token = uptoken(bucket, key);
        // console.log(up_token)
        const extra = new qiniu.form_up.PutExtra()
        const formUploader = new qiniu.form_up.FormUploader(config)
        //要上传文件的本地路径
        filePath = './ruby-logo.png'
        var res_2 = formUploader.putFile(up_token, key, files.file.path, extra, function (err, result) {
            if (err) {
                console.log(err)
                return
            }
            // console.log(res)
            var response = {flag: true, url: 'http://q92vb3yye.bkt.clouddn.com/' + key}
            var response_2 = JSON.stringify(response)
            res.end(response_2)
        })
        //上传成功
        // console.log(res_2)
        // if (res_2.flag){
        //     res.end({flag:true,url:'http://q92vb3yye.bkt.clouddn.com/'+key})
        // }
    })
})


// 四_一： 获取店铺账号信息
app.post('/store/getStoreBack', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var store_id = req.body.store_id;
    // console.log(store_id)
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select * from store_back where store_id = ?';
    var params_1 = [store_id];
    var res_1 = await con(sql_1, params_1);
    if (res_1.length > 0) {
        // res_1 = JSON.stringify(res_1)
        //2.2 [0]取出数组的第一个元素
        var res_2 = res_1[0];
        //3.可以查到  返回信息
        var result = {
            flag: true,
            message: 'find success',
            data: {
                store_id: res_2.store_id,
                username: res_2.username,
                password: res_2.password,
                phone_num: res_2.phone_num
            }
        }
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    }
})


//四_二  更新账户
app.post('/store/update', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var store_id = req.body.store_id;
    var username = req.body.username;
    var password = req.body.password;
    var phone_num = req.body.phone_num;
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select * from store_back where store_id = ?';
    var params_1 = [store_id];
    var res_1 = await con(sql_1, params_1);
    if (res_1.length > 0) {
        //3.可以查到 更新该用户信息
        var sql_2 = 'update store_back set password = ? ,phone_num = ? where store_id = ?'
        var params_2 = [password, phone_num, store_id]
        var res_2 = await con(sql_2, params_2);
        var result = {flag: true, message: 'update success'}
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    }
})


//四_三  更新店铺信息
app.post('/store/update/msg', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var store_id = req.body.store_id;
    var storeName = req.body.storeName;
    var store_announce = req.body.store_announce;
    var location = req.body.location;
    var type_id = req.body.type_id;
    var store_img_url = req.body.store_img_url;
    var perCapita = req.body.perCapita;
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select * from store_msg where store_id = ?';
    var params_1 = [store_id];
    var res_1 = await con(sql_1, params_1);
    if (res_1.length > 0) {
        //3.可以查到 更新该用户信息store/update/msg
        var sql_2 = 'update store_msg set storeName = ? ,store_announce = ? ,location = ? ,type_id = ? ,store_img_url = ? ,perCapita = ? where store_id = ?'
        var params_2 = [storeName, store_announce, location, type_id, store_img_url, perCapita, store_id]
        var res_2 = await con(sql_2, params_2);
        var result = {flag: true, message: 'update success'}
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    }
})
// 四_四： 获取店铺账号信息
app.get('/store/getStoreMsg', async function (req, res) {
    //1.获取请求参数
    var {store_id} = url.parse(req.url, true).query;
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select * from store_msg where store_id = ?';
    var params_1 = [store_id];
    var res_1 = await con(sql_1, params_1);
    if (res_1.length > 0) {
        // console.log(res_1)
        // res_1 = JSON.stringify(res_1)
        //2.2 [0]取出数组的第一个元素
        var res_2 = res_1[0];
        // console.log(res_2)
        //3.可以查到  返回信息
        var result = {
            flag: true,
            message: 'find success',
            data: {
                store_img_url: res_2.store_img_url,
                storeName: res_2.storeName,
                store_announce: res_2.store_announce,
                perCapita: res_2.perCapita,
                location: res_2.location,
                type_id: res_2.type_id
            }
        }
        var string = JSON.stringify(result);
        // console.log(string)
        res.end(string)
    } else {
        res.end(JSON.stringify({flag: false, message: 'no such store'}))
    }
})

//五: 获取店铺分类信息
app.get("/store/getCategoryByStoreId", function (req, res) {
    //0.获取用户电话
    let {store_id} = url.parse(req.url, true).query;
    // console.log(store_id);
    if (store_id == 'undefined') {
        res.end("no store_id")
        return;
    }
    //1.定义sql语句
    var sql = "SELECT * FROM food_cate  WHERE parrent_id = ? and store_id = ?";
    //2.查询
    connection.query(sql, [0, store_id], function (error, result) {
        //出错了直接return
        if (error) {
            console.log(error);
            return;
        }
        //解析数据 为[{}]类型
        var result_2 = {flag: true, data: result}
        var orderList = JSON.stringify(result_2);
        res.end(orderList);
    });
});
//五-一 ：添加商品
app.post('/store/addGood', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var store_id = req.body.store_id;
    var food_name = req.body.food_name;
    var food_msg = req.body.food_msg;
    var food_price = req.body.food_price;
    var food_pic = req.body.food_pic;
    var value = req.body.value;
    var storeName = req.body.storeName;
    //2.查询对应的父id
    var sql_1 = 'select food_id from food_cate where value = ? and store_id  = ?'
    var res_1 = await con(sql_1, [value, store_id])
    var parrent_id = res_1[0].food_id
    //2.2 查询店铺图片
    var sql_1_1 = 'select store_img_url from store_msg where store_id = ?'
    var res_1_1 = await con(sql_1_1, [store_id])
    var store_img_url = res_1_1[0].store_img_url
    //3.可以查到 添加商品信息  添加商品时初始销量为0
    var sql_2 = 'insert into food_cate(food_name , food_pic ,food_msg ,food_sales , food_price ,parrent_id,store_id,storeName,store_img_url,value) values(?,?,?,?,?,?,?,?,?,?) '
    var params_2 = [food_name, food_pic, food_msg, 0, food_price, parrent_id, store_id, storeName, store_img_url, value]
    var res_2 = await con(sql_2, params_2);
    var food_id = res_2.insertId
    //3.添加详情信息
    var sql_3 = 'insert into food_detail values(?,?,?,?,?,?,?,?,?,?)'
    var params_3 = [store_id, food_id, store_img_url, food_name, food_msg, food_pic, storeName, 0, food_price, false]
    // console.log(params_3)
    var res_3 = await con(sql_3, params_3)
    //设置返回信息
    var result = {flag: true, message: 'update success'}
    var string = JSON.stringify(result);
    res.end(string)
})

//五-二  添加店铺分类信息
app.post('/store/addCate', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var food_name = req.body.food_name;
    var value = req.body.value;
    var store_id = req.body.store_id;

    //2.连接数据库查询是否有该用户
    var sql_1 = 'insert into food_cate(food_name , isActive , parrent_id ,store_id , value) values (?,?,?,?,?)';
    var params_1 = [food_name, 'false', 0, store_id, value];
    var res_1 = await con(sql_1, params_1);
    var result = {flag: true, message: 'insert success'}
    var string = JSON.stringify(result);
    // console.log(string)
    res.end(string)
})
//五-二  根据类别查询商品  暂时废弃
app.post('/store/edit', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var value = req.body.value;
    var store_id = req.body.store_id;
    // console.log(value)
    // console.log(store_id)
    //2.连接数据库查询是否有该用户
    var sql_1 = 'select * from food_cate where parrent_id = (select food_id from food_cate where store_id = ? and value = ?) ';
    var params_1 = [store_id, value];
    var res_1 = await con(sql_1, params_1);
    // console.log(res_1)
    // var result = getStoreMsg{flag: true, message: 'insert success'}
    // var string = JSON.stringify(result);
    // // console.log(string)
    // res.end(string)
})

//六_一: 获取店铺分类信息
app.get("/store/getGoodsByCateValueAndStoreId", async function (req, res) {
    //0.获取用户电话
    let {value} = url.parse(req.url, true).query;
    let {store_id} = url.parse(req.url, true).query;
    if (value == 'undefined' || store_id == 'undefined') {
        res.end(JSON.stringify({flag: false, message: "no cate"}))
        return;
    }
    //1.定义sql语句
    var sql_1 = "SELECT food_id FROM food_cate  WHERE value = ? and store_id = ?";
    //2.查询
    var res_1 = await con(sql_1, [value, store_id])
    if (res_1.length > 0) {
        var food_id = res_1[0].food_id
        var sql_2 = "select * from food_cate where parrent_id = ?"
        var res_2 = await con(sql_2, [food_id])
        if (res_2.length > 0) {
            var res_3 = JSON.stringify(res_2)
            var res_4 = JSON.parse(res_3)
            res.end(JSON.stringify({flag: true, message: 'find success', data: res_4}))
        }
    }
});
//六-二 删除商品
app.post('/store/good/del', urlencodedParser, async function (req, res) {
    //1.获取请求参数
    var food_id = req.body.food_id;
    var store_id = req.body.store_id;
    if (store_id == 'undefined' || food_id == undefined) {
        res.end(JSON.stringify({flag: false,}))
        return
    }
    //2.连接数据库查询是否有该用户
    var sql_1 = 'delete from food_cate where food_id = ? and store_id = ?';
    var params_1 = [food_id, store_id];
    var res_1 = await con(sql_1, params_1);
    res.end(JSON.stringify({flag: true, message: 'delete success'}))
    // var result = getStoreMsg{flag: true, message: 'insert success'}
    // var string = JSON.stringify(result);
    // // console.log(string)
    // res.end(string)
})
//七_一  获取未消费订单列表
app.get("/store/getOrderList", async function (req, res) {
    //0.获取店铺id
    let {store_id} = url.parse(req.url, true).query;
    if ( store_id == 'undefined') {
        res.end(JSON.stringify({flag: false, message: "no cate"}))
        return;
    }
    //1.定义sql语句
    var sql_1 = "SELECT * FROM order_list  WHERE  store_id = ?  and orderInformation = ?";
    //2.查询
    var res_1 = await con(sql_1, [ store_id , '待消费'])
    if (res_1.length >= 0) {
        //3.查询成功
        res.end(JSON.stringify({flag:true , message:'search success', data:JSON.parse(JSON.stringify(res_1))}))
    }else {
        res.end(JSON.stringify({flag:false,message:'search false'}))
    }
});
 //七_二  获取已消费订单列表
app.post("/store/getOrderHistory",urlencodedParser, async function (req, res) {
    //0.获取店铺id
    var store_id = req.body.store_id;
    if ( store_id == 'undefined') {
        res.end(JSON.stringify({flag: false, message: "no cate"}))
        return;
    }
    //1.定义sql语句
    var sql_1 = "SELECT * FROM order_list  WHERE  store_id = ?  and orderInformation = ?";
    //2.查询
    var res_1 = await con(sql_1, [ store_id , '已消费'])
    if (res_1.length > 0) {
        //3.查询成功
        res.end(JSON.stringify({flag:true , message:'search success', data:JSON.parse(JSON.stringify(res_1))}))
    }else {
        res.end(JSON.stringify({flag:false,message:'search false'}))
    }
});

//七_三  改变消费状态  该商品销量+1
app.post("/store/changeOrder",urlencodedParser, async function (req, res) {
    //0.获取店铺id
    var store_id = req.body.store_id;
    var order_id = req.body.order_id;
    if ( store_id == 'undefined' ||order_id == 'undefined') {
        res.end(JSON.stringify({flag: false, message: "no such order"}))
        return;
    }
    //1.定义sql语句
    var sql_1 = "update order_list set orderInformation = ? where store_id = ? and order_id = ?";
    var sql_2 = 'update food_cate set food_sales = food_sales + 1 where store_id = ? and food_name = (select food_name from order_list where order_id = ?)'
    var sql_3 = 'update food_detail set food_sales = food_sales + 1 where store_id = ? and food_name = (select food_name from order_list where order_id = ?)'
    //2.查询
    //3. 更新销量
    var res_2 = await con(sql_2,[store_id,order_id])
    var res_3 = await con(sql_3,[store_id,order_id])
    var res_1 = await con(sql_1, [ '已消费', store_id ,order_id])
    if (res_1.affectedRows == 1) {
        //3.修改成功
        res.end(JSON.stringify({flag:true , message:'update success'}))
    }else {
        // 修改失败
        res.end(JSON.stringify({flag:false,message:'update false'}))
    }
});

//  八 获取七天前的每天的会员总量  根据订单查询  对用户去重
app.get("/store/getGrowth", async function (req, res) {
    //0.获取店铺id
    let {store_id} = url.parse(req.url, true).query;
    if ( store_id == 'undefined') {
        res.end(JSON.stringify({flag: false, message: "no cate"}))
        return;
    }
    //1.定义sql语句
    var sql_1 = "SELECT * FROM order_list  WHERE  store_id = ?  and orderInformation = ?";
    //2.查询
    var res_1 = await con(sql_1, [ store_id , '待消费'])
    if (res_1.length >= 0) {
        //3.查询成功
        res.end(JSON.stringify({flag:true , message:'search success', data:JSON.parse(JSON.stringify(res_1))}))
    }else {
        res.end(JSON.stringify({flag:false,message:'search false'}))
    }
});





//接收post请求的参数
var reqon = function (req, res) {
    return new Promise(function (resolve, reject) {
        var body = '';
        req.on('data', function (chunk) {
            body += chunk;
        });
        req.on('end', function () {
            //4.解析post参数
            body = JSON.parse(body);
            if (body == null) {
                reject(body);
                return;
            } else {
                resolve(body);
            }
        });
    });
}



//监听80端口
app.listen(80);
console.log("----------------------分割---------------------------");
